import os,pickle,sys

from path import path

if sys.platform == 'win32':
    startfile = os.startfile
else:
    startfile = lambda f : os.system('gedit %s' % f)

class Resource:
    def __init__(self,name,data):
        print "newres",name,data
        self.name = name
        self._data = data
    def data(self):
        return self._data
    def activate(self):
        print "null activate",self.name

class FileResource(Resource):
    """ basic files, double-click opens """
    def activate(self):
        startfile(path(self.data()['loc']) / self.name )
        
class ResourceBunch:
    def __init__(self):
        self.res = {} # dict of lists (path -> [resources])
        self.recs = []
        self.nil = []

    def add_newitem_listener(self,lst):
        self.nil.insert(0,lst)
    
    def newitem(self,path,item):
        poslst = self.res.get(path,[])
        poslst.append(item)
        self.res[path]  = poslst
        # notify
        for l in self.nil:
            l(path,item)

    def refresh_newitem_listener(self):
        for path,item in self.res.items():
            for it in item:
                for l in self.nil:
                    l(path,it)
            
            
    def load(self,fname):
        data = pickle.load(path(fname).open())
        self.res = data
        self.refresh_newitem_listener()
    
    def save(self,fname):
        pickle.dump(self.res, path(fname).open('w'))
        
    def add_recognizer(self,r):
        """ recog should return (path,Resource) or None """
        self.recs.insert(0,r)
        
    def drop_item(self,item):
        for r in self.recs:
            ret = r(item)
            if ret is None:
                continue
            path, res = ret
            self.newitem(path, res)
            return

            
def basic_file_recognizer(item):
    print "filerecog",item
    fil = False
    try:
        fil = os.path.isfile(item)
    except:
        pass
    if not fil:
        return None
    # it's a file, put it in ext folder
    basen = os.path.basename(item)
    path = os.path.dirname(item)
    ext = os.path.splitext(basen)[1]
    r = FileResource(basen, {'loc' : path } )
    return (ext, r)
    